import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2022-10-28
 * Time: 16:30
 */
public class Test {
    public static void main(String[] args) {
        int[] array = {100,45,16,89,4,67,23};
        HeapSort(array);
        System.out.println(Arrays.toString(array));
    }

    private static void HeapSort(int[] array) {
        creatBigheap(array);
        int end = array.length-1;
        while (end > 0){
            swap(array,0,end);
            shifDown(array,0,end);
            end --;
        }
    }

    private static void creatBigheap(int[] array) {
        for (int parent = (array.length-1-1)/2; parent >= 0 ; parent--) {
            shifDown(array,parent,array.length);
        }
    }

    private static void shifDown(int[] array, int parent, int len) {
        int child = 2*parent +1;
        while (child < len){
            if (child + 1 < len && array[child+1]> array[child]){
                child++;
            }
            if(array[parent] < array[child]){
                swap(array,parent,child);
                parent = child;
                child = 2*parent +1;
            }else {
                break;
            }
        }
    }

    private static void swap(int[] array, int parent, int child) {
        int tmp = array[parent];
        array[parent] = array[child];
        array[child] = tmp;
    }
}

